<template>
  <div>
    <h1>考勤管理</h1>
    <div v-for="courseSchedule in courseStore.teacherCourses" :key="courseSchedule.id">
      <div class="course-header">
        <h2>{{ courseSchedule.course.courseName }} 课程考勤</h2>
        <el-button type="primary" @click="toggleStudents(courseSchedule)">
          {{ courseSchedule.isExpanded ? '折叠' : '展开' }}
        </el-button>
      </div>
      <div v-if="courseSchedule.isExpanded">
        <el-table :data="courseSchedule.students" stripe>
          <el-table-column prop="studentNumber" label="学生 ID"></el-table-column>
          <el-table-column prop="name" label="学生姓名"></el-table-column>
          <el-table-column label="考勤操作">
            <template #default="scope">
              <el-button
                type="success"
                :disabled="scope.row.attendanceStatus === 'absent'"
                @click="recordAttendance(scope.row,courseSchedule.id, 'present')"
                >出勤</el-button
              >
              <el-button
                type="warning"
                :disabled="scope.row.attendanceStatus === 'absent'"
                @click="recordAttendance(scope.row,courseSchedule.id, 'late')"
                >迟到</el-button
              >
              <el-button
                type="info"
                :disabled="scope.row.attendanceStatus === 'absent'"
                @click="recordAttendance(scope.row, courseSchedule.id,'leaveEarly')"
                >早退</el-button
              >
              <el-button
                type="danger"
                @click="recordAttendance(scope.row, courseSchedule.id,'absent')"
                >缺勤</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { useCourseStore } from '../stores/course';

import { useAttendanceStore } from '../stores/attendance';
import { ElButton, ElTable, ElTableColumn } from 'element-plus';
import type { TeacherCourse } from '@/types/course';
import type { Student } from '@/types/student';

const courseStore = useCourseStore();

const attendanceStore = useAttendanceStore();

// 初始化每个课程的折叠状态，默认展开
courseStore.teacherCourses.forEach(course => {
  if (!course.isExpanded) {
    course.isExpanded = true;
  }
});

const toggleStudents = (course:TeacherCourse) => {
  course.isExpanded = !course.isExpanded;
};

const recordAttendance = (student: Student, courseScheduleId:number,status: string) => {

  attendanceStore.recordAttendance(student.studentNumber,courseScheduleId, status);  
  student.attendanceStatus = status;
};

onMounted(async () => {
  // 获取老师所授课的具体课程
  await courseStore.fetchTeacherCourses();
});
</script>

<style scoped>
.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}
</style>